package edu.uoc.tdp.pac3.server;

import javax.swing.SwingUtilities;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.net.MalformedURLException;
import java.net.ConnectException;
import edu.uoc.tdp.pac3.common.tools.TDSLanguageUtils;
import java.awt.Color;

/**
 * Clase Server
 * 
 * @author Eloi Rebollo i Francesc Cabrera
 * @version 1.0
 */
public class Servidor extends JFrame {

    //private static final long serialVersionUID = 1L;
    private JPanel jContentPane = null;
    private JLabel lblStatus = null;
    private JButton btnRun = null;
    private JButton btnStop = null;
    private TDSLanguageUtils mess = null;
    private boolean flag = false;
    private GestorInscripcionsImpl objServices = null;

    /**
     * This is the default constructor
     */
    public Servidor() {
        super();
        initialize();
    }

    /**
     * This method initializes this
     * 
     * @return void
     */
    private void initialize() {
        //  existeix l'arxiu de misatges         
        messagesFile();
        this.setSize(475, 150);
        this.setContentPane(getJContentPane());
        this.setTitle(mess.getMessage("server.title"));        
        btnRun.setText(mess.getMessage("server.run"));
        btnStop.setText(mess.getMessage("server.stop"));
        setStatus();
    }

    /**
     * Comprova l’existència de l'arxiu de missatges
     * 
     * @return void
     */
    private void messagesFile() {
        //           
        boolean exist = mess.setDefaultLanguage("i18n/messages");
        if (!exist) {
            System.out.println("No es possible iniciar l'aplicació, no existeix l'arxiu de misatges 'i18n/messages*.properties'");
            System.exit(-1);
        }
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                Servidor thisClass = new Servidor();
                thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                thisClass.setVisible(true);
            }
        });
    }

    /**
     * Inicialitza l'objecte remot 
     * 
     * @throws RemoteException
     * @return void
     */
    private void initObjecteRemot() throws RemoteException {
        flag = false;
        //
        if (objServices == null) {
            objServices = new GestorInscripcionsImpl();
        }
    }

    /**
     * Arrancada del servidor de RMI
     * 
     * @throws RemoteException
     * @throws MalformedURLException
     * @throws ConnectException
     * @return void
     */
    private void runServer() throws RemoteException, MalformedURLException, ConnectException {
        if (objServices == null) {
            initObjecteRemot();
        }

        Naming.rebind("//localhost/Services", objServices);
        flag = true;
        setStatus();
    }

    /**
     * Aturada del servidor RMI
     * 
     * @throws RemoteException
     * @throws MalformedURLException
     * @throws NotBoundException
     * @return void
     */
    private void stopServer() throws RemoteException, MalformedURLException, NotBoundException {
        Naming.unbind("//localhost/Services");
        flag = false;
        setStatus();
    }

    /**
     * Mostra el JFrame segons l'estat de la connexio
     * 
     * @return void
     */
    private void setStatus() {
        if (!flag) {
            lblStatus.setText(mess.getMessage("server.status.stoping"));
            lblStatus.setForeground(Color.RED);
            btnRun.setEnabled(true);
            btnStop.setEnabled(false);
        } else {
            lblStatus.setText(mess.getMessage("server.status.running"));
            btnRun.setEnabled(false);
            btnStop.setEnabled(true);
        }
    }

    /**
     * This method initializes jContentPane
     * 
     * @return javax.swing.JPanel
     */
    private JPanel getJContentPane() {
        if (jContentPane == null) {
            lblStatus = new JLabel();
            lblStatus.setBounds(20, 15, 347, 16);
            lblStatus.setText("");
            jContentPane = new JPanel();
            jContentPane.setLayout(null);
            jContentPane.add(lblStatus, null);
            jContentPane.add(getRun(), null);
            jContentPane.add(getStop(), null);
        }
        return jContentPane;
    }

    /**
     * This method initializes Iniciar (Arranca el servidor)
     * 	
     * @return javax.swing.JButton	
     */
    private JButton getRun() {
        if (btnRun == null) {
            btnRun = new JButton();
            btnRun.setBounds(20, 50, 200, 50);
            btnRun.addActionListener(new java.awt.event.ActionListener() {

                public void actionPerformed(java.awt.event.ActionEvent e) {
                    try {
                        runServer();
                        lblStatus.setForeground(Color.GREEN);
                    } catch (RemoteException e1) {
                        JOptionPane.showMessageDialog(null,
                                mess.getMessage("server.err.rmi"),
                                mess.getMessage("server.err"), JOptionPane.ERROR_MESSAGE);
                    } catch (ConnectException e2) {
                        JOptionPane.showMessageDialog(null,
                                mess.getMessage("server.err.rmi"),
                                mess.getMessage("server.err"), JOptionPane.ERROR_MESSAGE);
                    } catch (MalformedURLException e3) {
                        // path incorrecte
                        JOptionPane.showMessageDialog(null,
                                mess.getMessage("server.err.rmi"),
                                mess.getMessage("server.err"), JOptionPane.ERROR_MESSAGE);
                    } catch (Exception eAl) {
                        // Altres errors
                        JOptionPane.showMessageDialog(null,
                                eAl.toString(),
                                mess.getMessage("errors"), JOptionPane.ERROR_MESSAGE);
                    }
                }
            });
        }
        return btnRun;
    }

    /**
     * This method initializes Parar (Atura el servidor)
     * 	
     * @return javax.swing.JButton	
     */
    private JButton getStop() {
        if (btnStop == null) {
            btnStop = new JButton();
            btnStop.setBounds(240, 50, 200, 50);
            btnStop.addActionListener(new java.awt.event.ActionListener() {

                public void actionPerformed(java.awt.event.ActionEvent e) {
                    try {
                        stopServer();
                        lblStatus.setForeground(Color.RED);
                    } catch (RemoteException e1) {
                        JOptionPane.showMessageDialog(null,
                                mess.getMessage("server.err.end.ok"),
                                mess.getMessage("server.err"), JOptionPane.ERROR_MESSAGE);
                    } catch (MalformedURLException e2) {
                        // ruta incorrecta
                        JOptionPane.showMessageDialog(null,
                                mess.getMessage("server.err.end"),
                                mess.getMessage("server.err"), JOptionPane.ERROR_MESSAGE);
                    } catch (NotBoundException e3) {
                        // error 
                        JOptionPane.showMessageDialog(null,
                                mess.getMessage("server.err.end"),
                                mess.getMessage("server.err"), JOptionPane.ERROR_MESSAGE);
                    } catch (Exception eAl) {
                        // Altres
                        JOptionPane.showMessageDialog(null,
                                eAl.toString(),
                                mess.getMessage("errors"), JOptionPane.ERROR_MESSAGE);
                    }
                }
            });
        }
        return btnStop;
    }
}
